package com.sljy.hzk.ui.task;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.example.api.InjectParam;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sljy.hzk.R;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.base.UserInfo;
import com.sljy.hzk.entity.TaskDatabaseEntity;
import com.sljy.hzk.entity.TaskDetailEntity;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.net.BaseCallBack;
import com.sljy.hzk.net.CommonResult;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.TaskService;
import com.sljy.hzk.room.AppDataBase;
import com.sljy.hzk.room.dao.TaskDao;
import com.sljy.hzk.ui.fragment.TaskFragment;
import com.sljy.hzk.util.EventListenerManager;
import com.sljy.hzk.util.NetWorkUtils;
import com.sljy.hzk.util.TimeUtils;
import com.sljy.hzk.view.NoScrollViewPager;
import com.sljy.hzk.view.adapter.ProgressAdapter;
import com.tkk.api.RxEventProcessor;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindDrawable;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE;
import static com.sljy.hzk.annotation.ActivityInfo.TITLE_TWO_LEVEL;

@ActivityInfo(layout = R.layout.activity_task_execute, isShowActionBar = true ,title = "巡检执行")
public class TaskExecuteActivity extends BaseActivity {
    @InjectParam int workPlanId;
    @InjectParam boolean isFromLocal = false;
    @InjectParam int workType;
    @InjectParam boolean isFinish = false;
    @BindView(R.id.viewpager) NoScrollViewPager viewpager;
    List<TaskFragment> fragments = new ArrayList<>();
    @BindView(R.id.img_next) ImageView imgNext;
    @BindView(R.id.img_back) ImageView imgBack;
    @BindDrawable(R.drawable.shape_task_bg) Drawable drawableLast;
    @BindDrawable(R.drawable.shape_task_bg) Drawable drawableLastCan;
    @BindDrawable(R.drawable.shape_task_bg) Drawable drawableNext;
    @BindDrawable(R.drawable.shape_task_bg) Drawable drawableNextCan;
    @BindView(R.id.progress_text)TextView progessText;
    private List<TaskDetailEntity> taskDetailEntityList = new ArrayList<>();
    FragmentPagerAdapter adapter;
    private int nowPos = 0;
    private int errorPage = 0;
    boolean isLoadSuss ;
    UserEntity user;
    TaskDao taskDao;
    private int maxTaskNum;
    @BindView(R.id.rl_view)
    RecyclerView rlView;
    @BindView(R.id.tv_up)
    ImageButton tv_up;
    List<String> weekList;
    private ProgressAdapter progressAdapter;
    private LinearLayoutManager linearLayoutManager;
    TaskDao roomData;
    @Override
    protected void init() {
        TaskExecuteActivity__JumpCenter.bind(this);
        roomData = AppDataBase.getInstance().getTaskDao();
        imgBack.setVisibility(View.GONE);
        imgNext.setVisibility(View.GONE);
        tv_up.setVisibility(View.GONE);
        viewpager.setScroll(false);
        weekList = new ArrayList<>();
        linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rlView.setLayoutManager(linearLayoutManager);
        user = UserInfo.getUserInfo();
        taskDao = AppDataBase.getInstance().getTaskDao();
        adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        };
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            @Override
            public void onPageSelected(int position) {
                nowPos = position;
                int itemPos = nowPos + 1;
                setImgRes();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        if (isFromLocal){
            isLoadSuss = true;
            Gson gson = new Gson();
            setData(gson.fromJson(AppDataBase.getInstance().getTaskDao().get(workPlanId), new TypeToken<List<TaskDetailEntity>>() {}.getType()));
        }else {
            HttpHeper.get().create(TaskService.class)
                    .getTaskDetail(workPlanId)
                    .compose(getThread())
                    .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new BaseCallBack<List<TaskDetailEntity>>(this) {
                        @Override
                        public void onCallBackSuccess(List<TaskDetailEntity> data) {
                           setData(data);
                           isLoadSuss = true;
                        }

                        @Override
                        public void onFail(String mes) {
                            showToast(mes);
                            isLoadSuss = false;
                        }
                    });

        }
    }

    private void initListener() {
        //点击滑动到中心，同时中心放大
        progressAdapter.setOnProgressClickListener(new ProgressAdapter.OnProgressClickListener() {
            @Override
            public void scrollMid(int position) {
                //因为一屏幕是5个，将点击的控件-2置为第一个，中间位置则为第三个
                progressAdapter.changePostion(position);
//                if (position-2>=0){
//                    linearLayoutManager.scrollToPositionWithOffset(position-2, 0);
//                    linearLayoutManager.setStackFromEnd(true);
//                }
                nowPos = position;
                viewpager.setCurrentItem(position, true);
                setImgRes();
            }
        });
        rlView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                //滚动暂停
                if (newState == SCROLL_STATE_IDLE ){

                    int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
                    int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                    if(lastVisibleItemPosition == maxTaskNum-1)
                        firstVisibleItemPosition++;
                    //progressAdapter.changePostion(firstVisibleItemPosition+2);
                    linearLayoutManager.scrollToPositionWithOffset(firstVisibleItemPosition, 0);
                    linearLayoutManager.setStackFromEnd(true);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

            }
        });

    }

    private void initView() {
        //设置recycleview
        if (progressAdapter==null){
            progressAdapter = new ProgressAdapter(this,weekList);
            rlView.setAdapter(progressAdapter);
        }else {
            progressAdapter.notifyDataSetChanged();
        }
    }


    private void setData(List<TaskDetailEntity> data){
        if(data.size() <= 1){
            if(isFinish)
                tv_up.setVisibility(View.GONE);
            else
                tv_up.setVisibility(View.VISIBLE);
            progessText.setVisibility(View.GONE);
        }

        weekList.clear();
        taskDetailEntityList.addAll(data);
        int num = 1;
        for (TaskDetailEntity taskDetailEntity : data) {
            Log.d("TaskFragment", ">>>setData---" );
            fragments.add(TaskFragment.get(taskDetailEntity));
            weekList.add(String.valueOf(num));
            num++;
        }
        maxTaskNum = num-1;
        viewpager.setAdapter(adapter);
        progessText.setText("已完成:0/"+maxTaskNum);
        setImgRes();
        initView();
        initListener();
    }

    private boolean UpCheck(boolean isShowToast){
        if(workType == 2){
            if(isShowToast)
                showToast("不能上传逾期任务");
            return false;
        }else if(workType == 3){
            if(isShowToast)
                showToast("不能上传已完成的任务");
            return false;
        }
        return true;
    }

    /**
     * TODO:图片先压缩再上传
     * 交卷
     * 1:循环每一个task是否完成
     */
    @SuppressLint("CheckResult")
    @OnClick(R.id.tv_up)
    void up() {
        if(isFinish){
            return;
        }
        if(!NetWorkUtils.isNetworkConnected(this)){
            saveDataToDao("网络连接失败，是否继续提交？");
            return;
        }

        TaskService taskService = HttpHeper.get().create(TaskService.class);
        Observable.just(taskDetailEntityList)
                .subscribeOn(Schedulers.io())
                .flatMap(taskDetailEntityList -> {
                    for (int i = 0; i < taskDetailEntityList.size(); i++) {
                        TaskDetailEntity detailEntity = taskDetailEntityList.get(i);
                        for (TaskDetailEntity.Subitem subitem : detailEntity.getList()) {
                            if (subitem.isRequired()) {
                                if ((subitem.isEditType() && TextUtils.isEmpty(subitem.getEditStr())) || (subitem.isChoseType() && !subitem.isHaveChosed())) {
                                    return Observable.error(new MyThrowable(i));
                                }
                            }
                        }
                        detailEntity.upPic();
                    }
                    Log.d(TAG, ">>>up---" +  taskDetailEntityList.toString());
                    return taskService.submit(workPlanId, user.getCpId(), taskDetailEntityList.toString(), user.getName());
                })
                .doOnNext(objectCommonResult -> {
                    if (isFromLocal){
                        //TODO
                       // taskDao.delete(new TaskDatabaseEntity(workPlanId,taskDetailEntityList.toString(), "",UserInfo.getUserInfo().getUserId()));
                    }
                })
                .doOnError(( throwable) -> {
                    if (throwable instanceof  MyThrowable){
                        MyThrowable myThrowable = (MyThrowable) throwable;
                        errorPage = myThrowable.getPos();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseCallBack<Object>(this) {
                    @Override
                    public void onCallBackSuccess(Object data) {
                        showToast("上传成功",R.drawable.uploadsuccess);
                        RxEventProcessor.get().post("dataHaveChange");
                        //移除本地缓存
                        if(roomData != null){
                            List<TaskDatabaseEntity> list = roomData.getUserAll(UserInfo.getUserInfo().getUserId());
                            for(TaskDatabaseEntity l : list){
                                if(l.getWorkPlanId() == workPlanId)
                                    roomData.delete(l);
                            }
                        }
                        finish();
                    }
                    @Override
                    public void onFail(String mes) {
                        showToast(mes,R.drawable.fail);
                        OnNoDoPage();
                    }
                });
    }

    public void OnNoDoPage(){
        if(errorPage != nowPos)
            this.viewpager.setCurrentItem(errorPage, true);
    }

    @OnClick(R.id.img_next)
    public void onImgNextClicked() {
        if (nowPos != taskDetailEntityList.size() - 1) {
            //顶部产生滑动
            progressAdapter.changePostion(nowPos + 1);
            onScrollProgress(nowPos + 1);
            viewpager.setCurrentItem(nowPos + 1, true);
        }
    }

    @OnClick(R.id.img_back)
    public void onImgBackClicked() {
        if (nowPos != 0) {
            //顶部产生滑动
            progressAdapter.changePostion(nowPos - 1);
            onScrollProgress(nowPos - 1);
            viewpager.setCurrentItem(nowPos - 1, true);
        }
    }

    private void onScrollProgress(int position){
        if (position-2>=0){
            linearLayoutManager.scrollToPositionWithOffset(position-2, 0);
            linearLayoutManager.setStackFromEnd(true);
        }
    }


    /**
     * 根据位置设置，上一项，下一项的背景图
     */
    private void setImgRes() {
        checkIsMust();
        imgBack.setVisibility(nowPos == 0 ? View.GONE : View.VISIBLE);
        imgNext.setVisibility(nowPos == taskDetailEntityList.size() - 1 ? View.GONE : View.VISIBLE);
        //imgNext.setImageDrawable(nowPos == taskDetailEntityList.size() - 1 ? drawableNext : drawableNextCan);
    }

    @Override
    protected boolean isShouldHideInput(View v, MotionEvent event) {
        return false;
    }

    @Override
    protected void onBackClick() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        if (!isLoadSuss){
            finish();
            return;
        }
        if(isFinish){
            finish();
            return;
        }
        saveDataToDao("未完成当前任务，退出前\n是否保存到本地");
    }

    private void saveDataToDao(String str){

        showExitDialog(str, R.drawable.fail);

//        new MaterialDialog.Builder(this)
//                .content(str)
//                .positiveText("保存到本地")
//                .onPositive((dia, v) -> {
//                    //TODO
//                    if (isFromLocal){
//                        taskDao.update(new TaskDatabaseEntity(workPlanId,taskDetailEntityList.toString(),"",UserInfo.getUserInfo().getUserId()));
//                    }else {
//                        taskDao.insert(new TaskDatabaseEntity(workPlanId,taskDetailEntityList.toString(),"",UserInfo.getUserInfo().getUserId()));
//                        RxEventProcessor.get().post("dataHaveChange");
//                    }
//                    showToast("保存成功");
//                    finish();
//                })
//                .negativeText("直接退出")
//                .onNegative((dialog, which) -> {
//                    finish();
//                })
//                .show();
    }

    @Override
    protected void OnDialogBtnClick(boolean isSure){
        if(isSure){
            Gson json = new Gson();
            if (isFromLocal){
                TaskDatabaseEntity entity =  taskDao.getWork(workPlanId);
                entity.setDataJson(json.toJson(taskDetailEntityList));
                taskDao.update(entity);
               //taskDao.update(new TaskDatabaseEntity(workPlanId,taskDetailEntityList.toString(),TimeUtils.dateToStr(TimeUtils.getNowDate()),UserInfo.getUserInfo().getUserId()));
            }else {
                TaskDatabaseEntity entity =  taskDao.getWork(workPlanId);
                if(entity != null){
                    entity.setDataJson(json.toJson(taskDetailEntityList));
                    taskDao.update(entity);

                }else{
                    taskDao.insert(new TaskDatabaseEntity(workPlanId,json.toJson(taskDetailEntityList),TimeUtils.dateToStr(TimeUtils.getNowDate()),UserInfo.getUserInfo().getUserId()));
                }
                RxEventProcessor.get().post("dataHaveChange");
            }
            finish();
        }
    }


    public class MyThrowable extends Throwable{
        int pos;
        public MyThrowable(int pos) {
            super("请完成当前页任务再进行提交");
            this.pos = pos;
        }
        public int getPos() {
            return pos;
        }

        public void setPos(int pos) {
            this.pos = pos;
        }
    }

    /**
     * 是否必填没有完成
     * */
    private void checkIsMust(){
        if(progressAdapter==null)return;
        List<Integer> list = new ArrayList<Integer>();
        int num = taskDetailEntityList.size();
        boolean isNext = true;
        for (int i = 0; i < taskDetailEntityList.size(); i++) {
            isNext = true;
            TaskDetailEntity detailEntity = taskDetailEntityList.get(i);
            for (TaskDetailEntity.Subitem subitem : detailEntity.getList()) {
                if (subitem.isRequired()) {
                    if ((subitem.isEditType() && TextUtils.isEmpty(subitem.getEditStr())) || (subitem.isChoseType() && !subitem.isHaveChosed())) {
                       //设置默认颜色
                        isNext = false;
                        list.add(0);
                        num--;
                        break;
                    }
                }
            }
            if(isNext)
                list.add(1);
        }
        progessText.setText("已完成:"+num+"/"+maxTaskNum);
        progressAdapter.setHighBackGround(list);
        if(num >= maxTaskNum-1){
            if(!UpCheck(false))return;
            if(isFinish){
                tv_up.setVisibility(View.GONE);
            }else{
                tv_up.setVisibility(View.VISIBLE);
            }
            progessText.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    //注册事件
    @Override
    protected void registEvent(){
       super.registEvent();
    }

    //移除事件
    @Override
    protected void removeEvent(){
       super.removeEvent();
    }

}
